package com.example.opengldemo._11_.test;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;

import com.example.opengldemo.R;
import com.example.opengldemo.util.MatrixState;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class TextureImageView extends GLSurfaceView implements GLSurfaceView.Renderer {

    int textureId ;
    TextureImage textureImage ;

    public TextureImageView(Context context) {
        super(context);
        initConfigAndRenderer();

    }

    private void initConfigAndRenderer() {
        this.setEGLContextClientVersion(3);
        setRenderer(this);
        this.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    @Override
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
        GLES30.glClearColor(0.5f, 0.5f, 0.5f, 1f);
        GLES30.glEnable(GLES30.GL_DEPTH_TEST);
        Bitmap locationResour = getLocationResour();
        textureId = initTexture(locationResour);
        locationResour.recycle();

        textureImage = new TextureImage(TextureImageView.this) ;

        MatrixState.setInitStack();
        GLES30.glDisable(GLES30.GL_CULL_FACE);
    }

    @Override
    public void onSurfaceChanged(GL10 gl10, int i, int i1) {
        GLES30.glViewport(0, 0, i, i1);
        float ratio = (float) i / i1;
        MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 1, 10);
        MatrixState.setCamera(0, 0, 2f, 0, 0, 0f, 0f, 1.0f, 0.0f);
    }

    @Override
    public void onDrawFrame(GL10 gl10) {
        GLES30.glClear(GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
        textureImage.drawSelf(textureId);

    }

    public Bitmap getLocationResour(){
        return BitmapFactory.decodeResource(TextureImageView.this.getResources(), R.drawable.waswas);
    }
    public int initTexture(Bitmap bitmap){
        int[] textureID = new int[1];
        GLES30.glGenTextures(1 , textureID , 0);
        int textureid = textureID[0] ;
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D , textureid);
        GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D , GLES30.GL_TEXTURE_MIN_FILTER , GLES30.GL_NEAREST);
        GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D , GLES30.GL_TEXTURE_MAG_FILTER , GLES30.GL_LINEAR);
        GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D , GLES30.GL_TEXTURE_WRAP_S , GLES30.GL_MIRRORED_REPEAT);
        GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D , GLES30.GL_TEXTURE_WRAP_T , GLES30.GL_MIRRORED_REPEAT);
        GLUtils.texImage2D(GLES30.GL_TEXTURE_2D , 0 , bitmap , 0);
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D , 0);
        return textureid ;
    }
}
